package threads;

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

import android.os.Handler;

public class DecodeImageThread implements Runnable {
	private int port;
	private DatagramSocket socket;
	private ExecutorService threadPool = Executors.newCachedThreadPool();
	private boolean stopped = false;
	private Handler handler;
	
	public DecodeImageThread(int port, Handler handler){
		this.port = port;
		this.handler = handler;
		
		socket = null;
	}
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			socket = new DatagramSocket(port);
			byte [] buffer = new byte[20000];
			
			while(isStopped() == false){
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				socket.receive(packet);
				
				this.threadPool.execute(new DecodeImageWorker(handler, packet));
			}
			
			this.threadPool.shutdown();
			System.err.println("Decode Image thread shut down");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private synchronized boolean isStopped(){
		return this.stopped;
	}

	public synchronized void stop(){
		this.stopped = true;
		this.socket.close();
	}
}
